<template>
    <div class="mainbg">
        <div class="over" @touchmove="changePage" @touchstart="changePageStart" @wheel="e => e.preventDefault()"
            :style="{ transform: `translateX(-${currentPage * 100}vw)` }">
            <keep-alive>
                <draggable :disabled="canotDrag" v-for="(_, pageIndex) in componentOrder" :key="pageIndex"
                    v-model="componentOrder[pageIndex]" group="people" @end="endDrag" item-key="id" class="mainbox"
                    v-focus="changeCanDrag">
                    <template #item="{ element }">
                        <div :class="(element.card || element.t) + ' weiget'">
                            <div style="position: absolute;right:-10px;top:-10px;z-index: 99;" v-show="!canotDrag"
                                @click="removeWeiget(pageIndex, element.id)">
                                <img src="@/assets/close.svg">
                            </div>
                            <component :is="element.component" :pr="{ ...element }"></component>
                        </div>
                    </template>
                </draggable>
            </keep-alive>
        </div>
        <div class="addWeiget" v-show="!canotDrag">
            <div @click="addWeigetMenu = true">添加微件</div>
            <div @click="canotDrag = true">结束编辑</div>
        </div>
        <el-drawer v-model="addWeigetMenu" title="请选择微件" direction="btt" size="80%">
           
        </el-drawer>
    </div>
</template>
  
<script setup lang="ts">
import userApi from "@/api/user";
import { ElMessageBox, ElDrawer } from "element-plus";
import { ref, defineAsyncComponent, Ref, markRaw } from "vue";
import { useRouter } from "vue-router";
import capsuleCard from "@/components/main/capsuleCard.vue";
import bus from "@/libs/bus";
import draggable from 'vuedraggable'
import userType from "@/types/user"

const vFocus = {
    mounted: function (el: HTMLElement, binding: { value: Function }) {
        let t: number | null
        el.addEventListener('touchstart', function (e) {
            if ((e.target as null | HTMLElement)?.className.includes("mainbox")) return
            t = setTimeout(() => {
                e.preventDefault()
                t && binding.value()
                t && clearTimeout(t)
            }, 1e3)
        }, false)
        el.addEventListener('contextmenu', function (e) {
            if ((e.target as null | HTMLElement)?.className.includes("mainbox")) return
            e.preventDefault();
            canotDrag.value = false
        })
        el.addEventListener('touchend', function () {
            t && clearTimeout(t)
            t = null
        })
    }
}

let canotDrag = ref(true), addWeigetMenu = ref(false)
function changeCanDrag() {
    canotDrag.value = false
}
function removeWeiget(pageINdex: number, id: string) {
    componentOrder.value[pageINdex].splice(componentOrder.value[pageINdex].findIndex((w) => w.id == id), 1)
}
function endDrag() {
    localStorage.setItem("desktop", JSON.stringify(componentOrder.value.map(page=>page.map((com)=>{let temp={...com};temp.component=undefined;return temp}))))
}


const router = useRouter();

let user: Ref<userType> = ref({} as userType);

user.value = userApi.getMyInfo();

setTimeout(() => {
    bus.emit("changeState", ["middle", `欢迎${user.value.status}${user.value.name}`]);
}, 1e3);


let fnList: { [key: string]: Function } = {
    about: () => ElMessageBox.alert("", "Hey！"),
    openBlank: (url: string) => window.open(url, "_blank"),
    go: (r: string | Object) => { router.push(r) }
}
let mock = JSON.parse(localStorage.desktop)



interface com {
    t: string;
    component?: any;
    on?: string;
    cb?: Function | boolean;
    id: string;
    args?: Array<String>
}
type mainComponents = {
    [key: string]: com
}


const mainComponents: Ref<mainComponents> = ref({} as mainComponents)
const componentOrder: Ref<Array<Array<com>>> = ref([]);
mock.forEach((page: Array<any>, pageIndex: number) => {
    let temp: Array<com> = []
    page.forEach((com: com, index) => {
        if (!mainComponents.value[com.t]) {
            mainComponents.value[com.t] = markRaw(com.t == "capsuleCard" ? capsuleCard : defineAsyncComponent(() => import(`@/components/main/default/${com.t}.vue`)))
        }
        temp.push({
            ...com,
            component: mainComponents.value[com.t],
            cb: !!com.on && (() => fnList[com.on as keyof typeof fnList](...(com.args || []))),
            id: pageIndex + "" + index
        })
    })
    componentOrder.value.push(temp)
})


let currentPage: Ref<number> = ref(0), currentPageFlag: boolean = true, changeStart: number = 0

function changePageStart(e: TouchEvent) {
    changeStart = e.touches[0].pageX
    currentPageFlag = true
}

function changePage(e: TouchEvent) {
    let current = e.touches[0].pageX
    //start-current>0 往左滑
    if (currentPageFlag) {
        // alert(now.value)
        if (currentPage.value < componentOrder.value.length - 1 && changeStart - current > 100) {
            currentPage.value += 1
            currentPageFlag = false
        } else if (currentPage.value > 0 && changeStart - current < -100) {
            currentPage.value -= 1
            currentPageFlag = false
        }
    }
}

</script>
  
<style scoped>
.over {
    display: flex;
    transition: all 0.5s;
}

.over::-webkit-scrollbar {
    height: 0;
    background-color: red;
}

.mainbg {
    width: 100%;
    height: 100%;
    position: relative;
    overflow: hidden;
}

.mainbox {
    width: 100%;
    height: 100vh;
    background: url(https://funtabs.cn/images/wallpaper.JPG);
    background-size: 100% 100%;
    /*https://pic.imgdb.cn/item/64e0bf15661c6c8e54ce3778.jpg*/
    /* background-position: 0 50%; */

    user-select: none;
    box-sizing: border-box;
    display: grid;
    grid-template-columns: repeat(auto-fill, 165px);
    grid-auto-flow: dense;
    grid-auto-rows: 64px;
    gap: 2%;
    padding-top: 12px;
    justify-content: space-evenly;
    flex-shrink: 0;
}

.tools1 {
    display: flex;
    width: 80%;
    margin-left: 10%;
    margin-top: 1.25rem;
    flex-wrap: wrap;
    justify-content: space-between;
    align-content: stretch;
}

.toolCard {
    display: flex;
    align-items: center;
    margin-left: 30px;
}
</style>


<style scoped>
.superCard {
    grid-column-start: auto;
    grid-column-end: span 2;
    grid-row-start: auto;
    grid-row-end: span 2;
    background-color: white;
    border-radius: 12px;
    position: relative;
    /* aspect-ratio: 1 / 1;  */
}

.bigCard {
    grid-column-start: auto;
    grid-column-end: span 1;
    grid-row-start: auto;
    grid-row-end: span 2;
    background-color: white;
    border-radius: 15px;
    position: relative;
    /* aspect-ratio: 1 / 1;  */
}

.capsule {
    grid-column-start: auto;
    grid-column-end: span 1;
    grid-row-start: auto;
    grid-row-end: span 1;
    background-color: white;
    border-radius: 15px;
    padding: 10px;
    display: flex;
    align-items: center;
    position: relative;
    overflow: hidden;
}

.weiget {
    position: relative;
}

.addWeiget {
    height: 40px;
    position: fixed;
    bottom: 0;
    z-index: 999;
    width: 100%;
    left: 0;
}
</style>